package com.fram.service.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.fram.bean.sys.PaySearchResponse;
import com.fram.common.async.AsyncMethod;
import com.fram.common.auth.UserAuthMethod;
import com.fram.common.auth.UserAuthMethod.LoginRedisKey;
import com.fram.common.canstant.ErrCode;
import com.fram.common.exception.ProException;
import com.fram.common.exception.ProValiDataException;
import com.fram.common.util.PublicMethod;
import com.fram.common.util.base.BaseService;
import com.fram.common.util.json.JSONTools;
import com.fram.entity.LogsRequestAll;
import com.fram.entity.SysArea;
import com.fram.entity.SysInterfaceRule;
import com.fram.mapper.LogsRequestAllMapper;
import com.fram.mapper.SysAreaMapper;
import com.fram.mapper.SysInterfaceRuleMapper;
import com.fram.mapper.SysPaymentMapper;
import com.fram.service.SystemService;

/**
 * @作者： 陳曉鬆 @时间： 2020年4月26日 - 下午5:50:38 @description：->
 */
@Service("systemService")
public class SystemServiceImpl extends BaseService implements SystemService {

	private static Logger LOG = LoggerFactory.getLogger(SystemServiceImpl.class);

	@Autowired
	private SysInterfaceRuleMapper interfaceRuleMapper;

	@Autowired
	private SysAreaMapper areaMapper;

	@Autowired
	private SysPaymentMapper paymentMapper;

	@Autowired
	private LogsRequestAllMapper logsRequestAllMapper;

	@Autowired
	private AsyncMethod asyncMethod;

	@Override
	public SysInterfaceRule getInterfaceRule(String appKey) throws ProException {
		SysInterfaceRule interfaceRule = null;
		int datebase = 0;
		String key = "INTERFACE_" + appKey;
		// 判断redis是否有这个签名数据
		Object appKeyValue = redisService.get(datebase, key);
		if (!StringUtils.isEmpty(appKeyValue)) {
			interfaceRule = JSONTools.jsonStr2obj(appKeyValue.toString(), SysInterfaceRule.class);
			if (interfaceRule != null) {
				return interfaceRule;
			}
		}
		// 从数据库获取这个签名数据
		interfaceRule = interfaceRuleMapper.selectByAppKey(appKey);
		if (interfaceRule == null) {
			throw new ProValiDataException(ErrCode.ERR_INVALIDSECRET_NO_EXISTED.getReturnCode(), ErrCode.ERR_INVALIDSECRET_NO_EXISTED.getReturnMsg());
		}
		redisService.set(datebase, key, JSONTools.obj2json(interfaceRule), 24 * 60 * 60);
		return interfaceRule;
	}

	@Override
	public String refreshLoginToken(String token, String registrationId) {
		try {
			if (StringUtils.isEmpty(token) || "null".equals(token)) {
				return null;
			}
			LoginRedisKey loginRedisKey = UserAuthMethod.getLoginRedisKeyClass(token);
			Object obj = redisService.get(UserAuthMethod.LOGIN_REDIS_DB, loginRedisKey.getRedisKey());
			if (obj != null) {
				redisService.setExpire(UserAuthMethod.LOGIN_REDIS_DB, loginRedisKey.getRedisKey(), UserAuthMethod.LOGIN_REDIS_TIME);
				// 设置极光推送Id
				asyncMethod.setRegistrationId(loginRedisKey.getRedisKey(), obj.toString(), registrationId);
				return obj.toString();
			}
		} catch (Exception e) {
			LOG.error("-用户登录-刷新token异常-->token:{}\n-异常:{}", token, PublicMethod.printErrorTrace(e));
		}
		return null;
	}

	@Override
	public void verificationLoginToken(String token, String requestUrl, String loginValue) throws ProException {
		if (StringUtils.isEmpty(token)) {
			throw new ProValiDataException(ErrCode.USER_NO_LOGIN.getReturnCode(), ErrCode.USER_NO_LOGIN.getReturnMsg());
		}
		// 验证token
		UserAuthMethod.getLoginRedisKeyClass(token);
		if (StringUtils.isEmpty(loginValue)) {
			throw new ProValiDataException(ErrCode.USER_LOGIN_BE_OVERDUE.getReturnCode(), ErrCode.USER_LOGIN_BE_OVERDUE.getReturnMsg());
		}
		// 单点登录判断最后登录时间是否一致
	}

	@Override
	public List<SysArea> searchAreaList(SysArea area) throws ProException {
		if (area.getLevel() == null) {
			area.setLevel(1);// 默认查询省/直辖市的数据
		}
		List<SysArea> list = areaMapper.select(area);
		if (list == null || list.size() == 0) {
			throw new ProValiDataException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		return list;
	}

	@Override
	public List<PaySearchResponse> payList(String view) throws ProException {
		if (StringUtils.isEmpty(view)) {
			view = "0";// 默认的支付方式
		}
		List<PaySearchResponse> list = paymentMapper.select(view);
		if (list == null || list.size() == 0) {
			throw new ProValiDataException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		return list;
	}

	@Override
	public void insertLogs(LogsRequestAll log) throws ProException {
		try {
			if (log.getRequestIoParam() != null && log.getRequestIoParam().length() >= 30000) {
				return;
			}
			if (log.getResponseParam() != null && log.getResponseParam().length() >= 30000) {
				return;
			}
			boolean xie = false;
			if (PublicMethod.isJson(log.getResponseParam()) || PublicMethod.isXML(log.getResponseParam())) {
				xie = true;
			}
			if (xie && log != null && !StringUtils.isEmpty(log.getRequestUrl()) && !log.getRequestUrl().contains("/log/")) {
				logsRequestAllMapper.insertSelective(log);
			}
		} catch (Exception e) {
		}
	}

}
